package seatiger.tomcat.catalina.session;

import seatiger.tomcat.catalina.Lifecycle;
import seatiger.tomcat.catalina.LifecycleException;
import seatiger.tomcat.catalina.LifecycleListener;
import seatiger.tomcat.catalina.Session;
import seatiger.tomcat.catalina.util.LifecycleSupport;

import java.util.List;

/**
 * session管理器的标准实现
 */
public class StandardManager extends ManagerBase implements Lifecycle, Runnable {

    private LifecycleSupport lifecycle = new LifecycleSupport(this);
    private boolean started = false;

    /**
     * 线程是否结束
     */
    private boolean threadDone = false;


    private int checkInterval = 60;

    private Thread thread = null;

    @Override
    public void addLifecycleListener(LifecycleListener listener) {
        lifecycle.addLifecycleListener(listener);
    }

    @Override
    public List<LifecycleListener> findLifecycleListeners() {
        return lifecycle.findLifecycleListeners();
    }

    @Override
    public void removeLifecycleListener(LifecycleListener listener) {
        lifecycle.removeLifecycleListener(listener);
    }

    @Override
    public void start() throws LifecycleException {
        if (started) {
            throw new LifecycleException("standardManager.alreadyStarted");
        }
        lifecycle.fireLifecycleEvent(START_EVENT, null);
        started = true;

        threadStart();
    }

    @Override
    public void stop() throws LifecycleException {
        if (!started) {
            throw new LifecycleException("standardManager.notStarted");
        }
        lifecycle.fireLifecycleEvent(STOP_EVENT, null);
        started = false;
    }

    /**
     * 启动后台线程
     */
    private void threadStart() {
        if (thread != null)
            return;
        threadDone = false;
        thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    @Override
    public void run() {
        while (!threadDone) {
            threadSleep();
            processExpires();
        }
    }

    private void threadSleep() {
        try {
            Thread.sleep(checkInterval * 1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 后台线程，周期行程检查过期session
     */
    private void processExpires() {
        Session[] sessions = findSessions();
        for (Session session : sessions) {
            session.isValid();
       }
    }
}
